package com.atguigu.gulimall.product.service.impl;

import com.atguigu.gulimall.product.entity.BrandEntity;
import com.atguigu.gulimall.product.service.BrandService;
import com.atguigu.gulimall.product.service.CategoryService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryBrandRelationDao;
import com.atguigu.gulimall.product.entity.CategoryBrandRelationEntity;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;


@Service("categoryBrandRelationService")
public class CategoryBrandRelationServiceImpl extends ServiceImpl<CategoryBrandRelationDao, CategoryBrandRelationEntity> implements CategoryBrandRelationService {

    private BrandService brandService;
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryBrandRelationEntity> page = this.page(
                new Query<CategoryBrandRelationEntity>().getPage(params),
                new QueryWrapper<CategoryBrandRelationEntity>().eq("brand_id",params.get("brandId"))
        );

        return new PageUtils(page);
    }

    @Override
    public void saveCategoryAndBrand(CategoryBrandRelationEntity categoryBrandRelation) {
        String brandName = this.brandService.getById(categoryBrandRelation.getBrandId()).getName();
        String categoryName = this.categoryService.getById(categoryBrandRelation.getCatelogId()).getName();
        this.baseMapper.insert(categoryBrandRelation.initNameInfo(brandName, categoryName));
    }

    @Override
    public List<BrandEntity> queryBrandListByCatId(Long catId) {
        List<Long> brandIds = this.baseMapper.selectList(new QueryWrapper<CategoryBrandRelationEntity>().eq("catelog_id", catId)).stream().map(CategoryBrandRelationEntity::getBrandId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(brandIds)) {
            return new ArrayList<>();
        }
        return brandService.listByIds(brandIds);
    }

    @Autowired
    public void setBrandService(BrandService brandService) {
        this.brandService = brandService;
    }

    @Autowired
    public void setCategoryService(CategoryService categoryService) {
        this.categoryService = categoryService;
    }
}
